import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref(JSON.parse(localStorage.getItem('user')) || null)
  const token = ref(localStorage.getItem('token') || '')
  
  // 计算属性
  const isAuthenticated = computed(() => !!userInfo.value)
  const userRole = computed(() => userInfo.value?.role || 'student')
  const isAdmin = computed(() => userRole.value === 'admin')
  const isTeacher = computed(() => userRole.value === 'teacher')
  const isStudent = computed(() => userRole.value === 'student')
  
  // 操作
  function setUser(user) {
    userInfo.value = user
    localStorage.setItem('user', JSON.stringify(user))
  }
  
  function setToken(newToken) {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }
  
  function logout() {
    userInfo.value = null
    token.value = ''
    localStorage.removeItem('user')
    localStorage.removeItem('token')
  }
  
  return {
    userInfo,
    token,
    isAuthenticated,
    userRole,
    isAdmin,
    isTeacher,
    isStudent,
    setUser,
    setToken,
    logout
  }
}) 